import { PublishBase } from "./PublishBase";
import { join, basename, dirname } from "path";
import { existsSync, mkdirSync, writeFileSync, copyFileSync } from "fs";
import * as rimraf from 'rimraf';
import { paserIndexJs, saveWebHtml } from "./PaserHtmlUtil";
import { createDirSync, cpDir, createManifest } from "../utils/FileUtil";

export class WebPublish3 extends PublishBase {
    get projDir(){return "web"}
    createProject() {
        let verPath = join(this._publishVo.toPath, this._version);
        if (existsSync(verPath)) {
            rimraf(verPath, (err) => {
                if (err) {
                    console.warn(`删除${verPath}出错`);
                    return;
                }
                this.doPack();
            });
        } else {
            this.doPack();
        }
    }


    doPack() {
        let verPath = join(this._publishVo.toPath, this._version);
        if (!existsSync(verPath)) {
            mkdirSync(verPath);
        }
    
        // 解析html文件
        let htmlObj = paserIndexJs(this._publishVo.fromPath);
    
        this.log('开始修改config.json');
        // 写入config
        let crtProjPath = join(this._publishVo.toPath, this._version);
        writeFileSync(join(crtProjPath, this.getConfigName()), this._publishVo.config);
    
        this.log('开始合并js代码');
        console.log('htmlObj.js', htmlObj.js);
        // 合并js列表
        /* mergeJs(htmlObj.js, publishVo, crtProjPath, 'code.js', (codeName: string) => {
            log(txtLog, '开始生成index.html文件');
            let cn = basename(codeName);
            createHtml(htmlObj.html, cn, crtProjPath, () => {
                log(txtLog, '开始hash素材');
                cpRes(crtProjPath);
            });
        }, packCfg.chkRelease); */
        this.cpWebJs(htmlObj.js, this._publishVo.fromPath, crtProjPath);
    }

    cpWebJs(jsList: string[], binPath: string, toPath: string, complete?: (codeName: string) => void) {
        /* let loginPath = join(binPath, 'login.html');
        if (existsSync(loginPath)) {
            copyFileSync(loginPath, join(toPath, 'login.html'));
        }
        let indexPath = join(binPath, 'index.html');
        if (existsSync(indexPath)) {
            copyFileSync(indexPath, join(toPath, 'index.html'));
        }
        let indexJsPath = join(binPath, 'index.js');
        if (existsSync(indexJsPath)) {
            copyFileSync(indexJsPath, join(toPath, 'index.js'));
        } */
        this.cpFile('./login.html', binPath, toPath);
        this.cpFile('./vue.min.js', binPath, toPath);
        this.cpFile('./vue.js', binPath, toPath);
        this.cpFile('./index.html', binPath, toPath);
        this.cpFile('./index.js', binPath, toPath);
    
        for (const iterator of jsList) {
            this.cpFile(iterator, binPath, toPath);
        }
        this.cpRes(toPath);
    }


    cpFile(fileUrl: string, binPath: string, toPath: string, cb?: () => void) {
        let dirName = fileUrl;
        let fileName = basename(fileUrl);
        if (fileUrl.indexOf('/') >= 0) {
            dirName = dirname(fileUrl);
        }
        let destPath = join(toPath, dirName);
        let fromPath = join(binPath, fileUrl);
        if(!existsSync(fromPath))return;
        createDirSync(destPath, () => {
            copyFileSync(fromPath, join(destPath, fileName));
        });
    }
    
    createHtml(htmlTxt: string, codeName: string, htmlPath: string, callback?: () => void) {
        let codeTemplate = `<script type="text/javascript" src="${codeName}"></script>\n`;
        let tempIdx = htmlTxt.indexOf('</body>');
        htmlTxt = htmlTxt.substr(0, tempIdx) + codeTemplate + htmlTxt.substr(tempIdx);
        // 将index.html写入web目录
        saveWebHtml(htmlTxt, htmlPath, () => {
            let loginPath = join(this._publishVo.fromPath, 'login.html');
            if (existsSync(loginPath)) {
                copyFileSync(loginPath, join(htmlPath, 'login.html'));
            }
            if (callback !== null) {
                callback();
            }
        });
    }
    
    cpRes(resPath: string) {
        if (!existsSync(resPath)) {
            mkdirSync(resPath);
        }
        // 拷贝素材
        cpDir(join(this._publishVo.fromPath, 'res'), join(resPath, 'res'), () => {
            createManifest(join(resPath, 'res'), (info) => {
                console.log('info;', info);
                if (info === null) {
                    console.log(`素材manifest: res_${this._version}.json 生成出错`);
                    return;
                }
                writeFileSync(join(resPath, `res_${this._version}.json`), JSON.stringify(info));
                this.log('素材拷贝完毕');
                this.packOver();
            }, this._publishVo.content.chkRelease ? 8 : 0); // 这里要注意最后的参数0, 如果不需要hash, 则为0, 需要结合chkRelease来判断
    
        }, this._publishVo.content.chkRelease, { dir: ['\W+\.svn'] });
    }

    getConfigName() {
        if (this._publishVo.plat) {
            return `config_${this._publishVo.plat}.json`;
        }
        return 'config.json';
    }
}